package daemon

import (
	"fmt"
	"github.com/rs/cors"
	"net/http"
	"path/filepath"
)

// StartMediaServer 启动媒体文件服务器
func StartMediaServer(port int, workFolder string) (err error) {
	// 创建新的多路复用器
	mux := http.NewServeMux()

	// 设置媒体文件服务
	fileServer := http.FileServer(http.Dir(filepath.Join(workFolder)))

	// 包装文件服务以处理CORS
	corsHandler := cors.New(cors.Options{
		AllowedOrigins: []string{
			"http://wails.localhost", // wails 中嵌入的浏览器默认域为 wails.localhost
			fmt.Sprintf("http://localhost:%d", port)},
		AllowedMethods:   []string{"GET", "HEAD", "OPTIONS"},
		AllowCredentials: true,
		Debug:            false,
	})
	// 设置路由
	mux.Handle("/media/", http.StripPrefix("/media/", corsHandler.Handler(fileServer)))
	// 启动服务器
	err = http.ListenAndServe(fmt.Sprintf("127.0.0.1:%d", port), mux)
	return
}
